import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/purchase_evaluation_project_odoo_api.dart';
import 'package:flutter_admin/models/odoo/purchase_evaluation_project.dart';
import 'package:flutter_admin/models/user.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../generated/l10n.dart';

class PurchaseEvaluationProjectEdit extends StatefulWidget {
  var templateName = '';
  String? templateId;
  List? deptIdValList;
  PurchaseEvaluationProjectEdit({
    this.purchaseEvaluationProject,
    required this.templateName,
    required this.templateId,
    required this.deptIdValList,
  });

  final PurchaseEvaluationProject? purchaseEvaluationProject;

  @override
  _PurchaseEvaluationProjectEditState createState() =>
      _PurchaseEvaluationProjectEditState();
}

class _PurchaseEvaluationProjectEditState
    extends State<PurchaseEvaluationProjectEdit> {
  late PurchaseEvaluationProject purchaseEvaluationProject;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);

  List<SelectOptionVO> templateList = [];
  List<SelectOptionVO> deptIdList = [];
  List<SelectOptionVO> deptUserList = [];

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.purchaseEvaluationProject == null;
    this.purchaseEvaluationProject =
        widget.purchaseEvaluationProject ?? PurchaseEvaluationProject();
    _loadSelectVO();
  }

  _loadSelectVO() async {
    templateList = await DynamicDataApi.getModelSelect(
      model: "purchase.evaluation.template",
      name: "template_name",
      active: false,
    );
    if (isAdd == true) {
      deptIdList = await DynamicDataApi.getModelSelect(
        model: "hr.department",
        name: "complete_name",
        key: "parent_id",
        operator: "!=",
        val: null,
        key2: 'id',
        operator2: 'not in',
        val2: widget.deptIdValList,
      );
    } else {
      deptIdList = await DynamicDataApi.getModelSelect(
        model: "hr.department",
        name: "complete_name",
        key: "parent_id",
        operator: "!=",
        val: null,
      );
    }
    purchaseEvaluationProject.templateName = widget.templateName;
    purchaseEvaluationProject.templateId = widget.templateId;
    setState(() {});
  }

  _loadDeptUsers(String value) async {
    /**
               * 
               * 选定部门后，需要刷新部门内的用户列表 
               * @Author: chendeji
               * @Date: 2022-05-23 18:32:56
              */
    deptUserList = await DynamicDataApi.getUserListByDeptID(data: {
      'domainList': [
        ['dept', '=', purchaseEvaluationProject.deptId],
        ['template', '=', widget.templateId]
      ]
    });
    // Fluttertoast.showToast(msg: '数据长度：${deptUserList.length}');
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '模板名称',
            enable: false,
            value: purchaseEvaluationProject.templateName,
            onSaved: (v) {
              purchaseEvaluationProject.templateName = v;
            },
          ),
          CryInput(
            width: 280,
            label: '考评项目',
            value: purchaseEvaluationProject.evaluationProject,
            onSaved: (v) {
              purchaseEvaluationProject.evaluationProject = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            width: 300,
            label: '评价部门',
            dataList: deptIdList,
            value: purchaseEvaluationProject.deptId,
            onChange: (value) async {
              purchaseEvaluationProject.deptId = value;
              _loadDeptUsers(value);
            },
            onSaved: (v) async {
              purchaseEvaluationProject.deptId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 280,
            label: '备注',
            value: purchaseEvaluationProject.comment,
            onSaved: (v) {
              purchaseEvaluationProject.comment = v;
            },
          ),
          CrySelect(
            width: 300,
            label: '考评人员',
            dataList: deptUserList,
            value: purchaseEvaluationProject.testerUid,
            onChange: (value) {
              purchaseEvaluationProject.testerUid = value;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            PurchaseEvaluationProjectOdooApi.saveOrUpdate(
                    purchaseEvaluationProject.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                //CryUtils.message(re s.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
            // });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
